package com.jokins.admin.vue.user.action;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jokins.admin.vue.user.actioncontext.SysUserChangePasswordDoc;
import com.jokins.admin.vue.user.mapper.SysUserMapper;
import com.jokins.admin.vue.user.param.SysUserChangePasswordParam;
import com.jokins.admin.vue.user.utils.FixedHashPasswordUtils;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.vue.user.SysUser;
import com.jokins.common.util.BusinessCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SysUserChangePasswordDocAction extends BaseAction<SysUserChangePasswordDoc> {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    protected void process(SysUserChangePasswordDoc actionContext) throws BusinessException {
        SysUserChangePasswordParam param = actionContext.getParam();
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id", param.getId());
        SysUser user = sysUserMapper.selectOne(wrapper);
        boolean isPasswordCorrect = FixedHashPasswordUtils.compareHashedPasswords(param.getOldPassword(), user.getSalt());
        if (!isPasswordCorrect) {
            throw new BusinessException("密码错误", BusinessCode.PARAM_ERROR);
        } else {
            String newPassword = FixedHashPasswordUtils.sha256Hash(param.getNewPassword());
            UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", param.getId());
            updateWrapper.set("password",param.getNewPassword());
            updateWrapper.set("salt",newPassword);
            int rowsAffected =  sysUserMapper.update(null, updateWrapper);
            if (rowsAffected == 0) {
                throw new BusinessException("Failed to update password",BusinessCode.SYSTEM_ERROR);
            }
            log.info("密码正确:{}", JSON.toJSONString(user));
        }
    }
}
